const ALL = 0;
const UNPAID = 1;
const UNSHIPPED = 2;
const REFUND = 3;
const statusEnum = {
  0: 'ALL',
  1: '未付款',
  2: '未发货',
  3: '退款'
};
Page({
  data: {
    ALL,
    UNPAID,
    UNSHIPPED,
    REFUND,
    tabs: [
      {
        id: ALL,
        title: '全部',
        onClick: () => { },
      },
      {
        id: UNPAID,
        title: '未付款',
        onClick: () => { },
      },
      {
        id: UNSHIPPED,
        title: '未发货',
        onClick: () => { },
      },
      {
        id: REFUND,
        title: '退款',
        onClick: () => { },
      }
    ],
    activeTabId: ALL,
    orderList: [
    ],
    "userId": {}
  },
  onShow() {
    this.orderList("ALL", 0);
    //this.fetchCurrentCommodities(this.data.activeTabId);
  },
  onLoad() {
    const app = getApp();
    const userInfo = app.globalData.userInfo;
    console.log(userInfo);
    if (userInfo == null) {
      abridge.alert({
        title: "获取个人信息失败，请稍后"
      })
      return
    }
    this.setData({
      userId: userInfo.user_id
    })
  },
  async orderList(status, id) {
    if (status == "ALL") {
      status = null;
    }
    const orderList = await my.fncontext.callFunction({
      name: "orderList",
      data: {
        "status": status,
        "userId": this.data.userId
      }
    });
    console.log('订单列表', orderList)
    this.setData({
      activeId: id,
      orderList: orderList.result
    })
  },
  //这个地方获取订单数据
  async ordersDetail(id) {
    console.log("ordersDetail id:", id);
    const ordersDetail = await my.fncontext.callFunction({
      name: "ordersDetail",
      data: {
        id: id
      }
    });
    console.log('ordersDetail one', ordersDetail)
    return ordersDetail;
  },
  //重新支付
  async rePay(event) {
    const app = getApp();
    const userInfo = app.globalData.userInfo;
    console.log(userInfo);
    if (userInfo == null) {
      abridge.alert({
        title: "获取个人信息失败，请稍后"
      })
      return
    }
    //1，通过id获取订单详情
    const id = event.currentTarget.dataset.id;
    const ordersDetail = await this.ordersDetail(id);
    console.log("ordersDetail:", ordersDetail);
    //2，支付
    await this.pay(ordersDetail.result._id, userInfo.user_id, ordersDetail.result.orderNo, ordersDetail.result.totalAmount);
    //重新获取订单数据
    this.onShow();
  },
  //重新支付
  async refund(event) {
    //1，通过id获取订单详情
    const id = event.currentTarget.dataset.id;
    const ordersDetail = await this.ordersDetail(id);
    console.log("ordersDetail:", ordersDetail);
    //2.退款
    var alipayTradeRefund = await my.fncontext.callFunction({
      name: "alipayTradeRefund",
      data: {
        outTradeNo: ordersDetail.result.orderNo,
        amount: ordersDetail.result.totalAmount
      }
    });
    console.log("alipayTradeRefund", alipayTradeRefund);
    if (alipayTradeRefund.result != null && alipayTradeRefund.result.fund_change == "Y") {
      await this.updateOrderStatus(id, statusEnum[3])
    }
    await this.onShow();
  },
  async pay(...params) {
    const id = params[0];
    const userId = params[1];
    const tradeNo = params[2];
    const total = params[3];
    console.log("params", params);
    if (!userId) {
      my.showToast({
        content: '输入userId',
        duration: 1000
      });
      return;
    }
    // 云环境初始化 
    await my.fncontext.init();
    const trade = await my.fncontext.callFunction({
      name: "alipayTradeCreate",
      data: {
        "tradeNo": tradeNo,
        "totalAmount": total,
        "subject": "商品",
        "buyerId": userId
      }
    })
    console.log('trade', trade);
    if (trade != null && trade.result.code == "10000") {
      try {
        const result = await this.tradePaySync(trade.result);
        console.log("支付结果：", result);
        // 执行成功操作逻辑
        if (result.resultCode != null && result.resultCode == "9000") {
          await this.updateOrderStatus(id, statusEnum[2]);
        }
      } catch (error) {
        console.error(error); // 处理错误
      }
    }
  },
  async tradePaySync(trade) {
    console.log("支付参数：", trade.trade_no);
    return new Promise((resolve, reject) => {
      my.tradePay({
        tradeNO: trade.trade_no,
        success: function (res) {
          resolve(res); // 异步操作成功，解析Promise，并返回结果
        },
        fail: function (error) {
          reject(error); // 异步操作失败，拒绝Promise，并返回错误信息
        }
      });
    });
  },
  async updateOrderStatus(...params) {
    const orderId = params[0];
    const orderStatus = params[1];
    const response = await my.fncontext.callFunction({
      name: "orderUpdate",
      data: {
        "id": orderId,
        "status": orderStatus
      }
    });
    console.log("修改订单状态", response);
  },
  onTabItemTap(id) {
    console.log(id);
    this.orderList(statusEnum[id], id);
  }
});
